//
// Created by guo on 24-8-22.
//

#include "shm.h"
#include <sys/mman.h>
#include <fcntl.h>
#include <unistd.h>
#include <unordered_map>
#include <iostream>

struct MapInfo{
    std::string name;
    size_t size{0};
    char* data{nullptr};
};
std::unordered_map<std::string, MapInfo> g_keymap;

bool create_shm(const std::string& key, size_t size){
    //打开共享内存
    int shm_fd = shm_open(key.c_str(), O_CREAT | O_RDWR, 0666);
    if (shm_fd == -1) {
        std::cout << "shm_open failed !!!" << std::endl;
        return false;
    }

    //修改共享内存大小
    int ret;
    ret = ftruncate(shm_fd,(__off_t)size);
    if(ret == -1){
        std::cout << "ftruncate failed !!!" << std::endl;
        return false;
    }

    //映射共享内存到指针
    void* data = (char*)mmap(nullptr,size,PROT_READ | PROT_WRITE,MAP_SHARED,shm_fd,0);
    if(data == (void*)-1){
        std::cout << "mmap failed !!!" << std::endl;
        return false;
    }

    MapInfo info;
    info.name = key;
    info.size = size;
    info.data = (char*)data;

    g_keymap.insert(std::make_pair(key,info));

    return true;
}